def projects = [
    [
        name: 'test-service',
        jobName: 'pipeline-test-service',
        gitRepo: 'https://gitee.com/LingJianCode/jenkins-shared-lib.git',
        displayName: 'Test Service Pipeline',
        branch: 'master',
        scriptPath: 'jenkinsfile/study01.groovy',
        credentialId: ''
    ]
]
// environmentVariables需要envinject plugin支持
def createPipelineJob(Map project) {
    pipelineJob(project.jobName) {
        displayName(project.displayName)
        description("Automatically generated Pipeline Job for ${project.name}, branch: ${project.branch}, Jenkinsfile: ${project.scriptPath}")
        parameters {
            stringParam(
                'BRANCH',
                project.branch,
                'Git branch to build for ' + project.name
            )
        }
        environmentVariables{
            envs([
                DEPLOY_ENV: 'Test branch: ${BRANCH} environmentVariables DEPLOY_ENV: gray',
                APP_NAME: 'Test branch: ${BRANCH} environmentVariables APP_NAME: jenkins-shared-lib'
            ])
        }
        definition {
            cpsScm {
                scm {
                    git {
                        remote {
                            url(project.gitRepo)
                            // ✅ 只有当 credentialId 非空时才设置
                            if (project.credentialId?.trim()) {
                                credentials(project.credentialId)
                            }
                        }
                        branch('${BRANCH}')
                    }
                }
                scriptPath(project.scriptPath)
            }
        }
    }
}

// 循环创建多个 Pipeline Job
projects.each { project ->
    createPipelineJob(project)
}